package com.ht.activiti.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 另外一种跨域问题解决方式
 *
 * @author zhangfc
 * @date 2021/11/24 9:27
 */
@Configuration
@WebFilter(filterName = "crosFilter", urlPatterns = "/*")
@Slf4j
public class CrosFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("CrosFilter加载中>>>>>>>>>>>>>");
    }

    /**
     * 解决跨域支持的请求头
     *
     * @param request  请求
     * @param response 响应
     * @param chain    响应链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;

        HttpServletResponse servletResponse = (HttpServletResponse) response;
        //允许跨域的主机
        servletResponse.setHeader("Access-Control-Allow-Origin", "*");
        //允许跨域的方法
        servletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        servletResponse.setHeader("Access-Control-Max-Age", "3600");
        servletResponse.setHeader("Access-Control-Allow-Headers",
                "accept,accept-Language,x-requested-with,Content-Type" +
                        ",lyncmed-access-token,user-agent,userid,referer" +
                        ",refreshtoken,username,token");
        //放行
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }
}
